package com.google.code.drift.async_task;

import java.io.IOException;

import android.content.Context;
import android.os.Looper;
import android.widget.Button;

import com.google.code.drift.service.ServerConnection;
import com.google.code.drift.utils.DLog;

/**
 * 客户端心跳周期10分钟，服务器心跳检测周期15分钟
 * 
 * @author zkwlx
 * 
 */
public class HeartbeatTask extends Thread {

	boolean flag = true;

	int userId;
	
	public HeartbeatTask(int id) {
		userId = id;
	}

	@Override
	public void run() {
		ServerConnection connection = ServerConnection.getConnection();
		String id = userId + "";
		
		// 第一次先延迟10分钟
		synchronized (this) {
			try {
				this.wait(600000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		try {
			synchronized (this) {
				while (flag) {
					connection.sendMessage(id);
					this.wait(600000);// 10分钟
				}
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			DLog.w("心跳任务，异常退出！");
			connection.closeIOAndSocket();
			connection = null;
		}
		DLog.i("心跳任务正常退出！");
	}

	public synchronized void cancel() {
		flag = false;
		this.notifyAll();
	}

}
